package com.example.controller;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.entity.User;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.zip.GZIPInputStream;

/**
 * @author zhangguoqing
 * @date 2020/10/9
 * Description: TODO
 */
@RestController
public class RestTempController {
    @Autowired
    private RestTemplate restTemplate;
    // 天气预报接口
    private static final String WEATHER_URI = "http://wthrcdn.etouch.cn/weather_mini?city=北京";

    @RequestMapping("/exampleRestTemplate")
    public void exampleRestTemplate(){
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity("http://localhost:8089/testHttpClient", null, String.class);
        String body = stringResponseEntity.getBody();
        System.out.println(body);
        JSONArray objects = JSONObject.parseArray(body);
        for (int i = 0; i < objects.size(); i++) {
            User object = objects.getObject(i, User.class);
            System.out.println(object.getName());
        }
    }


    /**
     * 天气预报
     */
    @RequestMapping()
    public String getWeather() {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8));
        HttpEntity<String> httpEntity = new HttpEntity<String>(null, httpHeaders);
        ResponseEntity<String> responseEntity = restTemplate.exchange(WEATHER_URI, HttpMethod.GET, httpEntity, String.class);
        String body = responseEntity.getBody();
        System.out.println(responseEntity);
        return body;
    }

    /**
     * 天气预报
     */
    @RequestMapping("/getWeather2")
    public String getWeather2() {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8));
        HttpEntity<String> httpEntity = new HttpEntity<String>(null, httpHeaders);
        ResponseEntity<String> responseEntity = restTemplate.exchange(WEATHER_URI, HttpMethod.GET, httpEntity, String.class);
        String body = responseEntity.getBody();
        System.out.println(responseEntity);
        return body;
    }

    @RequestMapping("/b")
    public void b(){
        String s = HttpUtil.get(WEATHER_URI);
        Object parse = JSONObject.parse(s);

        System.out.println(s);
    }


}
